package threadcoreknowledge.sixstates.scy;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 执行分析该过程,证明了Synchronized语句在未获得锁对象时,状态是Blocked
 * 同时,证明现在在sleep中,不会释放锁.
 */
public class ThreadStateBlock {
    public static void main(String[] args) throws Exception {

        Object object = new Object();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
                synchronized (object) {
                    System.out.println("thread1执行了----" + simpleDateFormat.format(new Date()));

                    try {
                        TimeUnit.SECONDS.sleep(8);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

//                    while (true) {
//
//                    }

                }
            }
        }, "thread1线程");

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
                synchronized (object) {
                    System.out.println("thread2执行了----" + simpleDateFormat.format(new Date()));

                    try {
                        TimeUnit.SECONDS.sleep(3);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

//                    while (true) {
//                    }
                }
            }
        }, "thread2线程");

        t1.start();
        t2.start();


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");


        while (true) {
            System.out.println("thread1线程状态:" + t1.getState() + "------" + simpleDateFormat.format(new Date()));
            System.out.println("thread2线程状态:" + t2.getState() + "------" + simpleDateFormat.format(new Date()));
            Thread.sleep(500);
            if (t1.getState().equals(Thread.State.TERMINATED)) {
                if (t2.getState().equals(Thread.State.TERMINATED)) {
                    break;
                }
            }
            System.out.println("---------------------------------");

        }


    }
}
